//
// ThreadAssist.cs
//
// Copyright (C) 2008 Lukas Lipka <lukaslipka@gmail.com>
//

using System;
using System.Threading;
using System.Runtime.InteropServices;
 
namespace Dashboard.Util
{
	public static class ThreadAssist
	{
		private static Thread main_thread = null;
		
		public static void Initialize ()
		{
			if (main_thread == null) {
				main_thread = Thread.CurrentThread;
			} else { 
				throw new ApplicationException ("main thread already set");
			}
		}
		
		public static void ProxyToMain (EventHandler handler)
		{
			if (!InMainThread) {
				Gtk.Application.Invoke (handler);
			} else {
				handler (null, new EventArgs());
			}
		}
		
		public static Thread Spawn (ThreadStart thread_start, bool auto_start)
		{
			Thread thread = new Thread (thread_start);
			thread.IsBackground = true;
			
			if (auto_start) {
				thread.Start ();
			}
			
			return thread;
		}
		
		public static Thread Spawn (ThreadStart thread_start)
		{
			return Spawn (thread_start, true);
		}
		
		public static bool InMainThread {
			get { return main_thread == Thread.CurrentThread; }
		}
	}
}